<template>
  <div class="qrcode-management-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>溯源码管理</span>
          <el-button type="primary" @click="openGenerateDialog" style="margin-right:600px">生成新溯源码</el-button>
        </div>
      </template>
      
      <el-table :data="qrCodes" stripe style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="产品名称" width="200">
          <template #default="scope">
            {{ getProductName(scope.row.productId) }}
          </template>
        </el-table-column>
        <el-table-column prop="batchNumber" label="批次号" width="160" />
        <el-table-column label="创建时间" width="180">
          <template #default="scope">
            {{ new Date(scope.row.createdAt).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column label="溯源码" width="160">
          <template #default="scope">
            <div class="qrcode-container">
              <!-- 使用生成的溯源码作为文本显示，实际项目中应该使用二维码图片 -->
              <span>{{ scope.row.code }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240">
          <template #default="scope">
<!--            <el-button size="small" @click="viewQRCode(scope.row)">查看</el-button>-->
<!--            <el-button size="small" type="success" @click="downloadQRCode(scope.row)">下载</el-button>-->
            <el-button size="small" type="danger" @click="deleteQRCode(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 生成新溯源码对话框 -->
    <el-dialog v-model="generateDialogVisible" title="生成新溯源码" width="500px">
      <el-form :model="generateForm" label-width="120px">
        <el-form-item label="产品">
          <el-select v-model="generateForm.productId" placeholder="选择产品">
            <el-option 
              v-for="product in products" 
              :key="product.id" 
              :label="product.name" 
              :value="product.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="批次号">
          <el-input v-model="generateForm.batchNumber" />
        </el-form-item>
        <el-form-item label="数量">
          <el-input-number v-model="generateForm.quantity" :min="1" :max="100" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="generateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitGenerate">确认生成</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 查看溯源码对话框 -->
    <el-dialog v-model="dialogVisible" title="查看溯源码" width="400px">
      <div class="qrcode-view-container" v-if="selectedQRCode">
        <div class="qrcode-image-large">
          <img :src="qrCodeImage" alt="溯源码" />
        </div>
        <div class="qrcode-info">
          <p><strong>产品：</strong>{{ getProductName(selectedQRCode.productId) }}</p>
          <p><strong>批次号：</strong>{{ selectedQRCode.batchNumber }}</p>
          <p><strong>创建时间：</strong>{{ selectedQRCode.createdAt }}</p>
          <p><strong>溯源链接：</strong>{{ selectedQRCode.traceUrl }}</p>
        </div>
        <div class="qrcode-actions">
          <el-button type="primary" @click="downloadQRCode(selectedQRCode)">下载</el-button>
          <el-button @click="dialogVisible = false">关闭</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { traceInfoAPI, productAPI } from '@/api/api'

export default {
  name: 'QRCodeManagement',
  setup() {
    // 数据定义
    const qrCodes = ref([])
    const products = ref([])
    const loading = ref(false)
    const dialogVisible = ref(false)
    const generateDialogVisible = ref(false)
    const selectedQRCode = ref(null)
    const qrCodeImage = ref('')
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    
    // 生成二维码的表单
    const generateForm = ref({
      productId: '',
      batchNumber: '',
      quantity: 1
    })
    
    // 获取二维码列表
    const fetchQRCodes = async () => {
      loading.value = true
      try {
        const params = {
          page: currentPage.value,
          size: pageSize.value
        }
        
        const response = await traceInfoAPI.getTraceInfoList(params)
        
        if (response.success) {
          qrCodes.value = response.data.traceCodes || []
          total.value = response.data.total || 0
        } else {
          ElMessage.error('获取溯源码列表失败: ' + response.message)
        }
      } catch (error) {
        console.error('获取溯源码列表失败:', error)
        ElMessage.error('获取溯源码列表失败: ' + (error.message || '未知错误'))
      } finally {
        loading.value = false
      }
    }
    
    // 获取产品列表
    const fetchProducts = async () => {
      try {
        const response = await productAPI.getProducts({
          pageNum: 1,
          pageSize: 100 // 获取尽可能多的产品
        })
        
        if (response && response.code === 200) {
          // 处理返回的数据
          const productData = response.data.list || response.data.content || response.data;
          
          // 确保productData是数组
          if (Array.isArray(productData)) {
            products.value = productData.map(item => {
              // 打印每个产品项的详细信息，便于调试
              console.log('产品项数据:', item);
              return {
                id: item.id,
                // 优先使用productName字段，因为后端API返回的是productName
                name: item.productName || item.name || `产品ID: ${item.id}`,
                batchNumber: item.batchNumber || item.batchId
              };
            });
            console.log('产品列表获取成功:', products.value);
          } else {
            console.error('产品数据不是数组:', productData);
            products.value = [];
          }
        } else {
          ElMessage.error('获取产品列表失败: ' + (response?.message || '未知错误'))
        }
      } catch (error) {
        console.error('获取产品列表失败:', error)
        ElMessage.error('获取产品列表失败: ' + (error.message || '未知错误'))
      }
    }
    
    // 打开生成对话框
    const openGenerateDialog = () => {
      generateForm.value = {
        productId: '',
        batchNumber: '',
        quantity: 1
      }
      generateDialogVisible.value = true
    }
    
    // 提交生成请求
    const submitGenerate = async () => {
      if (!generateForm.value.productId) {
        ElMessage.warning('请选择产品')
        return
      }
      
      if (!generateForm.value.batchNumber) {
        ElMessage.warning('请输入批次号')
        return
      }
      
      if (generateForm.value.quantity < 1 || generateForm.value.quantity > 100) {
        ElMessage.warning('生成数量应在1-100之间')
        return
      }
      
      try {
        const response = await traceInfoAPI.generateTraceInfo({
          productId: generateForm.value.productId,
          batchNumber: generateForm.value.batchNumber,
          quantity: generateForm.value.quantity
        })
        
        if (response.success) {
          ElMessage.success('溯源码生成成功')
          generateDialogVisible.value = false
          fetchQRCodes() // 刷新列表
        } else {
          ElMessage.error('溯源码生成失败: ' + response.message)
        }
      } catch (error) {
        console.error('溯源码生成失败:', error)
        ElMessage.error('溯源码生成失败: ' + (error.message || '未知错误'))
      }
    }
    
    // 查看二维码
    const viewQRCode = async (qrCode) => {
      try {
        const response = await traceInfoAPI.getTraceInfoById(qrCode.id)
        
        if (response.success) {
          selectedQRCode.value = response.data
          qrCodeImage.value = response.data.qrCodeUrl
          dialogVisible.value = true
        } else {
          ElMessage.error('获取溯源码详情失败: ' + response.message)
        }
      } catch (error) {
        console.error('获取溯源码详情失败:', error)
        ElMessage.error('获取溯源码详情失败: ' + (error.message || '未知错误'))
      }
    }
    
    // 下载二维码
    const downloadQRCode = async (qrCode) => {
      try {
        const response = await traceInfoAPI.downloadTraceInfo(qrCode.id)
        
        if (response.success) {
          // 创建一个链接并点击它来下载
          const link = document.createElement('a')
          link.href = response.data.downloadUrl
          link.download = `trace-${qrCode.id}.png`
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          
          ElMessage.success('溯源码下载成功')
        } else {
          ElMessage.error('溯源码下载失败: ' + response.message)
        }
      } catch (error) {
        console.error('溯源码下载失败:', error)
        ElMessage.error('溯源码下载失败: ' + (error.message || '未知错误'))
      }
    }
    
    // 删除二维码
    const deleteQRCode = (qrCode) => {
      ElMessageBox.confirm(
        '此操作将永久删除该溯源码，是否继续？',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(async () => {
          try {
            const response = await traceInfoAPI.deleteTraceInfo(qrCode.id)
            
            if (response.success) {
              ElMessage.success('溯源码删除成功')
              fetchQRCodes() // 刷新列表
            } else {
              ElMessage.error('溯源码删除失败: ' + response.message)
            }
          } catch (error) {
            console.error('溯源码删除失败:', error)
            ElMessage.error('溯源码删除失败: ' + (error.message || '未知错误'))
          }
        })
        .catch(() => {
          ElMessage.info('已取消删除')
        })
    }
    
    // 分页相关
    const handleSizeChange = (newSize) => {
      pageSize.value = newSize
      fetchQRCodes()
    }
    
    const handleCurrentChange = (newPage) => {
      currentPage.value = newPage
      fetchQRCodes()
    }
    
    // 获取产品名称
    const getProductName = (productId) => {
      const product = products.value.find(p => p.id === productId)
      return product ? product.name : `产品ID: ${productId || 'N/A'}`
    }
    
    // 生命周期钩子
    onMounted(() => {
      fetchQRCodes()
      fetchProducts()
    })
    
    return {
      qrCodes,
      products,
      loading,
      dialogVisible,
      generateDialogVisible,
      selectedQRCode,
      qrCodeImage,
      total,
      currentPage,
      pageSize,
      generateForm,
      openGenerateDialog,
      submitGenerate,
      viewQRCode,
      downloadQRCode,
      deleteQRCode,
      handleSizeChange,
      handleCurrentChange,
      getProductName
    }
  }
}
</script>

<style scoped>
.qrcode-management-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.qrcode-container {
  display: flex;
  justify-content: center;
}

.qrcode-image {
  width: 80px;
  height: 80px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.qrcode-view-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.qrcode-image-large {
  margin-bottom: 20px;
}

.qrcode-image-large img {
  width: 200px;
  height: 200px;
}

.qrcode-info {
  width: 100%;
  margin-bottom: 20px;
}

.qrcode-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
}
</style> 